use gloo::utils::document;
use shared::clone;
use wasm_bindgen::prelude::*;
use web_sys::HtmlElement;
use yew::prelude::*;

#[derive(Clone, PartialEq, Properties)]
pub struct DropdownProps {
    #[prop_or_default]
    pub children: Children,
}

#[function_component]
pub fn Dropdown(props: &DropdownProps) -> Html {
    let is_active = use_state_eq(|| false);
    let on_btn_click = Callback::from(clone!([is_active], move |_| {
        is_active.set(!*is_active);
    }));

    let _ = use_effect_with_deps(clone!([is_active], move |_| {
        let callback = Closure::<dyn Fn(MouseEvent)>::wrap(Box::new(move |event| {
            if let Some(elem) = event.target().and_then(|t| t.dyn_into::<HtmlElement>().ok()) {
                if let Some(_) = elem.closest(".dropdown-trigger").unwrap() {
                    return;
                }
            }
            is_active.set(false);
        }));
        let _ = document()
            .add_event_listener_with_callback("click", callback.as_ref().unchecked_ref());
        std::mem::forget(callback);
    }), ());

    let class = if *is_active {
        classes!("dropdown", "is-active")
    } else {
        classes!("dropdown")
    };

    html! {
        <div {class}>
            <div class="dropdown-trigger">
                <button onclick={on_btn_click}>{"···"}</button>
            </div>
            <div class="dropdown-content">
                {props.children.clone()}
            </div>
        </div>
    }
}
